//
//  WeatherViewController.swift
//  天气
//
//  Created by 邢胡斯盛 on 2024/10/7.
//

import UIKit
import CoreLocation

// MARK: - UIViewController
class WeatherViewController: UIViewController {
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var weatherDescriptionLabel: UILabel!
    
    var weatherManager: WeatherManager = WeatherManager()
    let locationManager: CLLocationManager = CLLocationManager()
    
    // 提示信息弹窗，当用户检索的城市不存在时作提示
    let alertCityNotExist = UIAlertController(title: "输入格式有误或该城市不存在", message: "输入格式有误或该城市不存在，请检查你的输入。", preferredStyle: UIAlertController.Style.alert)
    // 提示信息弹窗，当无法获取用户当前的位置信息时作提示
    let alertObtainLocationInformationFailed = UIAlertController(title: "位置信息获取失败", message: "无法获取你的位置信息，请确认授予了定位权限且定位功能已开启。", preferredStyle: UIAlertController.Style.alert)
    
    // 确认选项
    let okay1 = UIAlertAction(title: "好的", style: UIAlertAction.Style.cancel)
    let okay2 = UIAlertAction(title: "好的", style: UIAlertAction.Style.cancel)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 为两个提示信息弹窗添加确认选项（取消选项）
        alertCityNotExist.addAction(okay1)
        alertObtainLocationInformationFailed.addAction(okay2)
        
        // 将searchTextField的代理设置为本类
        searchTextField.delegate = self
        // 将WeatherManager的代理设置为本类
        weatherManager.delegate = self
        // 将locationManager的代理设置为本类
        locationManager.delegate = self
        
        // 向用户申请定位权限
        locationManager.requestWhenInUseAuthorization()
        // 获取用户当前的位置信息并且显示该位置的天气信息
        locationManager.requestLocation()
    }
}

// MARK: - UITextFieldDelegate
extension WeatherViewController: UITextFieldDelegate {
    // 搜索按钮被按下时的执行逻辑
    @IBAction func searchButtonPressed(_ sender: UIButton) {
        // 隐藏键盘
        searchTextField.endEditing(true)
    }
    
    // 键盘上的"Search"键被按下时的执行逻辑
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 隐藏键盘
        searchTextField.endEditing(true)
        // 返回用户向searchTextField中输入的内容
        return true
    }
    
    // 用户尝试结束向searchTextField的输入时的执行逻辑
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if searchTextField.text != "" {
            // 用户的输入非空时允许结束输入
            searchTextField.placeholder = "搜索城市的拼音"
            return true
        } else {
            // 用户的输入为空时作提示并且不允许用户结束输入
            searchTextField.placeholder = "搜索的城市不能为空"
            return false
        }
    }
    
    // searchTextField.endEditing函数调用后需要执行的逻辑
    func textFieldDidEndEditing(_ textField: UITextField) {
        // 获取指定城市的实时天气信息
        weatherManager.fetchWeather(cityName: searchTextField.text!)
        // 清空searchTextField中现有的内容
        searchTextField.text = ""
    }
}

// MARK: - WeatherManagerDelegate
extension WeatherViewController: WeatherManagerDelegate {
    func didUpdateWeather(weatherInfo: WeatherModel) {
        // 显示实时天气信息
        DispatchQueue.main.async {
            self.conditionImageView.image = UIImage(systemName: weatherInfo.conditionImageName)
            self.temperatureLabel.text = weatherInfo.temperatureString
            self.cityLabel.text = weatherInfo.cityName
            self.weatherDescriptionLabel.text = weatherInfo.weatherDescription
        }
    }
    
    func didFailWithWeather(error: any Error) {
        // 输出提示信息
        DispatchQueue.main.async {
            self.present(self.alertCityNotExist, animated: true)
        }
    }
}

// MARK: - CLLocationManagerDelegate
extension WeatherViewController: CLLocationManagerDelegate {
    // 定位按钮被按下时的执行逻辑
    @IBAction func locateButtonPressed(_ sender: UIButton) {
        // 获取用户当前的位置信息并且显示该位置的天气信息
        locationManager.requestLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // 获取用户的精确位置信息
        if let location = locations.last {
            // 停止更新用户的位置信息
            locationManager.stopUpdatingLocation()
            // 获取该位置的天气信息
            weatherManager.fetchWeather(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
        // 输出提示信息
        DispatchQueue.main.async {
            self.present(self.alertObtainLocationInformationFailed, animated: true)
        }
    }
}
